import { IFetchInterceptor } from './types';

export class FetchBusy implements IFetchInterceptor {
  private loadingProgress = 0;

  private readonly onBusy: (status: boolean) => void;

  constructor(onBusy: (status: boolean) => void) {
    this.onBusy = onBusy;
  }

  request(request: Request) {
    if (this.loadingProgress === 0) this.onBusy(true);
    this.loadingProgress += 1;
    return request;
  }

  response(response: Response) {
    this.loadingProgress -= 1;
    if (this.loadingProgress === 0) this.onBusy(false);
    return response;
  }

  requestError(error: any) {
    return this.error(error);
  }

  responseError(error: any) {
    return this.error(error);
  }

  private error(error: any) {
    this.loadingProgress -= 1;
    if (this.loadingProgress === 0) this.onBusy(false);
    return Promise.reject(error);
  }
}
